$(document).ready(function () {
  initSelect()
  initDatePick()

  initGroup()
  initStatistics()

  initTable()
})

/** 搜索 */
function searchBtn() {
  var formData = $('#form-data').serializeArray()
  console.log('formData', formData);
}

/** 重置 */
function resetBtn() {
  var form = document.getElementById('form-data')
  form.reset()
  initSelect()
  // 删除日期选择器
  $('.datePicker-x').remove()
}

/** 更多展开 */
function unfoldMore() {
  var formDom = $('#search-form-box')[0]
  var moreIconDom = $('#s-more-icon')[0]
  if (formDom.classList.toString().indexOf('s-df') >= 0) {
    formDom.classList.remove('s-df')
    formDom.classList.add('s-unfold')
    moreIconDom.classList.add('up')
  } else {
    formDom.classList.add('s-df')
    formDom.classList.remove('s-unfold')
    moreIconDom.classList.remove('up')
  }
}

/** init 表单下拉相关 */
function initSelect() {
  var year = xmSelect.render({
    name: 'year', // 表单提交时的 name
    el: '#year',
    tips: '请选择年份',
    radio: true, // 是否开启单选
    clickClose: true, // 是否在选择完毕之后关闭下拉菜单
    theme: {
      color: '#409eff',
    },
    model: {
      icon: 'hidden',
      label: {
        type: 'text',
        block: {
          //最大显示数量, 0:不限制
          showCount: 10,
          //是否显示删除图标
          showIcon: false,
        }
      }
    },
    initValue: [1],
    data: [{
        name: '所有',
        value: 1
      },
      {
        name: '2023',
        value: 2
      },
      {
        name: '2022',
        value: 3
      },
      {
        name: '2021',
        value: 4
      },
    ],
    on: function (v) {
      console.log('选择年份', v);
    }
  })
}

/** 日期时间相关 */
function initDatePick() {
  $('.wrap-time').on('click', function () {
    var _this = this;
    var reportTimeType = 5;
    var double = true;
    if (!$(this).next('[name="datePicker"]').length) {
      $(this).after("<div class='datePicker-x' name='datePicker'></div>");
      datePicker = $('.datePicker-x').datePicker({
        reportTimeType: reportTimeType, // 4代表小时、5代表天、6代表周、7代表月、8代表季、9代表年
        startDom: $(_this).find('input[name="startTime"]'), // 开始时间要赋值的DOM元素
        endDom: $(_this).find('input[name="endTime"]'), // 结束时间要赋值的DOM元素
        format: 'YYYY-MM-DD HH:mm:ss',
        fastTime: fastTime[double][reportTimeType], // 快速选择的时间
        isFast: true, // 是否显示快速选择的选项
        isDouble: double, // 是否双选择的日历
        disabledDate: false, // 是否禁用以后的时间
        showApplyButton: true,
        yes: function (startTime, endTime) { // 成功赋值前的回调可改变赋值的时间格式
        },
      });
    } else {
      if ($(this).next('[name="datePicker"]').hasClass('hide')) {
        $(this).next('[name="datePicker"]').removeClass('hide');
        datePicker.render();
      } else {
        $(this).next('[name="datePicker"]').addClass('hide');
      }
    }
  });
  // 监听点击其他地方关闭日期实现选择弹窗
  $(document).click(function (event) {
    var area = $('.datePicker-x')
    var area1 = $('.wrap-time')
    if ($(event.target).closest(area).length > 0 || $(event.target).closest(area1).length > 0) {
      // console.log('在里边');
    } else {
      $('.datePicker-x').addClass('hide')
    }
  })
}

/** ++++++++++++++++++++++++++++++++ 分组区 ++++++++++++++++++++++++++++++++++++ */
/** 分组项 */
var groupList = [
  // {
  //   label: '年份',
  //   value: 0
  // },
  // {
  //   label: '市',
  //   value: 1
  // },
  // {
  //   label: '机具大类',
  //   value: 4
  // },
  // {
  //   label: '机具小类',
  //   value: 5
  // },
  // {
  //   label: '分档名称',
  //   value: 8
  // },
]

/** 选中的分组项 */
var selectGroup = []
var temporarySelectGroup = []

/** 全部分组 */
var groupAll = [{
    text: '年份',
    value: 0
  },
  {
    text: '市',
    value: 1
  },
  {
    text: '县',
    value: 2
  },
  {
    text: '乡镇',
    value: 3
  },
  {
    text: '机具大类',
    value: 4
  },
  {
    text: '机具小类',
    value: 5
  },
  {
    text: '机具品目',
    value: 6
  },
  {
    text: '机具型号',
    value: 7
  },
  {
    text: '分档名称',
    value: 8
  },
  {
    text: '生产企业',
    value: 9
  },
  {
    text: '经销商',
    value: 10
  },
  {
    text: '申请结算批次',
    value: 11
  },
]
/** init 分组区 */
function initGroup() {
  // var groupDom = $('#group_box')
  var selectGroupDom = $('.group-select')
  var groupItemDoms = $('.group-item')

  // 清除上次生成的元素
  for (var i = 0; i < groupItemDoms.length; i++) {
    var item = groupItemDoms[i]
    item.remove()
  }

  groupList = []

  for (var i = 0; i < selectGroup.length; i++) {
    var item = selectGroup[i]
    groupAll.find(function (val) {
      if (item == val.value) {
        groupList.push(val)
      }
    })
  }

  for (var i = 0; i < groupList.length; i++) {
    var item = groupList[i]
    var divDom = createDom('div')
    divDom.className = 'group-item'
    divDom.innerText = item.text
    selectGroupDom.before(divDom)
  }
}

/** init 分组 dialog - 全部 */
function initGroupDialog() {
  var selectListDom = $('.select-list')[0]
  selectListDom.innerHTML = ''

  temporarySelectGroup = JSON.parse(JSON.stringify(selectGroup))

  for (var i = 0; i < groupAll.length; i++) {
    var item = groupAll[i]

    var liDom = createDom('li')
    liDom.className = 'flex-box'

    var divDom = createDom('div')
    divDom.className = 'custom-control custom-checkbox'

    var inputDom = createDom('input')
    var idx = temporarySelectGroup.indexOf(item.value)
    inputDom.className = 'custom-control-input'
    inputDom.id = 'select-item-' + item.value
    inputDom.type = 'checkbox'
    inputDom.checked = idx >= 0 ? true : ''
    inputDom.value = JSON.stringify(item)
    inputDom.onchange = function () {
      groupSelectChange(this, item)
    }

    var labelDom = createDom('label')
    labelDom.className = 'custom-control-label'
    labelDom.setAttribute('for', 'select-item-' + item.value)
    labelDom.innerText = item.text

    divDom.appendChild(inputDom)
    divDom.appendChild(labelDom)
    liDom.appendChild(divDom)
    $(selectListDom).append(liDom)
  }

  watchSelectItem()
  initGroupSelected()
}

/**
 * 单独选择
 * @param {*} e
 */
function groupSelectChange(e) {
  var item = e.value ? JSON.parse(e.value) : {}
  if (e.checked) {
    temporarySelectGroup.push(item.value)
  } else {
    var idx = temporarySelectGroup.indexOf(item.value)
    temporarySelectGroup.splice(idx, 1)
  }
  watchSelectItem()
}

/** 监测选中项修改全选状态 */
function watchSelectItem() {
  var selectListDom = $('.select-list')[0]
  var children = selectListDom.children
  if (temporarySelectGroup.length == 6) {
    for (let i = 0; i < children.length; i++) {
      const item = children[i];
      if (!item.children[0].children[0].checked) {
        item.children[0].children[0].disabled = true
      }
    }
  } else {
    for (let i = 0; i < children.length; i++) {
      const item = children[i];
      if (!item.children[0].children[0].checked) {
        item.children[0].children[0].disabled = false
      }
    }
  }
  var totalDom = $('.select-total')[0]
  // 选中数量
  totalDom.innerText = temporarySelectGroup.length + '/' + 6

  initGroupSelected()
}

/** init 分组 dialog = 已选 */
function initGroupSelected() {
  var selectedListDom = $('.selected-list')[0]
  selectedListDom.innerHTML = ''

  for (var i = 0; i < temporarySelectGroup.length; i++) {
    var selectItem = temporarySelectGroup[i]
    var item = groupAll.find(function (val) {
      if (val.value == selectItem) {
        return val
      }
    })

    var liDom = createDom('li')
    liDom.className = 'flex-box'

    var labelDom = createDom('div')
    labelDom.className = 'label'
    labelDom.innerText = item.text

    var opDom = createDom('div')
    opDom.className = 'selected-item-operation'

    var sDom1 = createDom('span')
    sDom1.className = 'selected-move-up'
    $(sDom1).attr('value', i)
    sDom1.onclick = function () {
      groupItemMoveUp($(this).attr('value'))
    }

    var sDom2 = createDom('span')
    sDom2.className = 'selected-move-down'
    $(sDom2).attr('value', i)
    sDom2.onclick = function () {
      groupItemMoveDown($(this).attr('value'))
    }

    var sDom3 = createDom('span')
    sDom3.className = 'selected-item-del'
    $(sDom3).attr('value', i)
    sDom3.onclick = function () {
      groupItemDel($(this).attr('value'))
    }

    liDom.appendChild(labelDom)
    opDom.appendChild(sDom1)
    opDom.appendChild(sDom2)
    opDom.appendChild(sDom3)
    liDom.appendChild(opDom)
    $(selectedListDom).append(liDom)
  }
}

/** 全部移出 */
function allShiftOut() {
  selectGroup = []
  temporarySelectGroup = []

  for (var i = 0; i < groupAll.length; i++) {
    var item = groupAll[i]
    var sDom = document.getElementById('select-item-' + item.value)
    sDom.checked = false
  }

  initGroupSelected()
  watchSelectItem()
}

/** 上移 */
function groupItemMoveUp(idx) {
  if (idx > 0) {
    var delItem = temporarySelectGroup.splice(idx, 1)[0]
    temporarySelectGroup.splice(idx - 1, 0, delItem)
    initGroupSelected()
  }
}

/** 下移 */
function groupItemMoveDown(idx) {
  idx = Number(idx)
  if (idx < temporarySelectGroup.length - 1) {
    var delItem = temporarySelectGroup.splice(idx, 1)
    temporarySelectGroup.splice(idx + 1, 0, delItem[0])
    initGroupSelected()
  }
}

/** 单独删除 */
function groupItemDel(idx) {
  var delItem = temporarySelectGroup.splice(idx, 1)[0]
  var item = groupAll.find(function (i) {
    if (i.value == delItem) {
      return i
    }
  })

  var dom = document.getElementById('select-item-' + item.value)
  dom.checked = false

  initGroupSelected()
  watchSelectItem()
}

/** 保存分组区弹窗选择 */
function saveGroupSelect() {
  selectGroup = JSON.parse(JSON.stringify(temporarySelectGroup))
  $('#groupModal').modal('hide')
  initGroup()
}

/** ++++++++++++++++++++++++++++++++ end 分组区 ++++++++++++++++++++++++++++++++++++ */

/** ++++++++++++++++++++++++++++++++ 统计区 ++++++++++++++++++++++++++++++++++++ */

/** 统计项 */
var statisticsList = [{
    label: '申请表数',
    value: 0
  },
  {
    label: '收益户数',
    value: 1
  },
  {
    label: '机具台数',
    value: 2
  },
  {
    label: '设施设备数量',
    value: 3
  },
  {
    label: '总功率',
    value: 4
  },
  {
    label: '中央补贴',
    value: 5
  },
  {
    label: '中央补贴结算',
    value: 6
  },
  {
    label: '省补贴',
    value: 7
  },
  {
    label: '省级配套资金',
    value: 8
  },
]

/** init 统计选项 */
function initStatistics() {
  var sDom = $('.statistics-box')[0]
  sDom.innerHTML = ''

  for (var i = 0; i < statisticsList.length; i++) {
    var item = statisticsList[i]

    var divDom = createDom('div')
    divDom.className = 'statistics-item custom-control custom-checkbox'

    var inputDom = createDom('input')
    inputDom.type = 'checkbox'
    inputDom.className = 'custom-control-input'
    inputDom.id = 'statistics-item-' + item.value

    var labelDom = createDom('label')
    labelDom.className = 'custom-control-label'
    labelDom.innerText = item.label
    $(labelDom).attr('for', 'statistics-item-' + item.value)

    divDom.appendChild(inputDom)
    divDom.appendChild(labelDom)

    sDom.appendChild(divDom)
  }
}

/** ++++++++++++++++++++++++++++++++ end 统计区 ++++++++++++++++++++++++++++++++++++ */

/**
 * init 数据列表
 */
function initTable() {
  /** 列表项 */
  var columns = [
    // {
    //   field: 'index',
    //   title: '',
    //   align: 'center',
    //   width: 50,
    //   valign: 'middle',
    //   checkbox: true
    //   // formatter: function (_v, _r, _i) {
    //   //   return _i + 1
    //   // }
    // },
    {
      field: 'applicationNumber',
      title: '申请表数',
      align: 'center',
      width: 100,
      valign: 'middle',
      formatter: paramsMatter
    },
    {
      field: 'earningsNumber',
      title: '受益户数',
      align: 'center',
      width: 100,
      valign: 'middle',
      formatter: paramsMatter
    },
    {
      field: 'implementNumbers',
      title: '机具台数',
      align: 'center',
      width: 100,
      valign: 'middle',
      formatter: paramsMatter
    },
    {
      field: 'quantityOfFacilities',
      title: '设施设备数量',
      align: 'center',
      width: 110,
      valign: 'middle',
      formatter: paramsMatter
    },
    {
      field: 'powers',
      title: '总功率',
      align: 'center',
      width: 160,
      valign: 'middle',
      formatter: paramsMatter
    },
    {
      field: 'centralSubsidies',
      title: '中央补贴',
      align: 'center',
      width: 100,
      valign: 'middle',
      // formatter: function (_v, _r, _i) {
      //   return _v == '1' ? 'PC端' : 'APP端'
      // }
    },
    {
      field: 'provincialSubsidies',
      title: '省补贴',
      align: 'center',
      width: 150,
      valign: 'middle',
      formatter: paramsMatter
    },
    {
      field: 'citySubsidies',
      title: '市补贴',
      align: 'center',
      width: 150,
      valign: 'middle',
      formatter: paramsMatter
    },
    {
      field: 'countySubsidies',
      title: '县补贴',
      align: 'center',
      width: 150,
      valign: 'middle',
      formatter: paramsMatter
    },
    {
      field: 'totalPurchasePrice',
      title: '购机总价',
      align: 'center',
      width: 100,
      valign: 'middle',
      formatter: paramsMatter
    },
    {
      field: 'centralSettlementFunds',
      title: '中央结算资金',
      align: 'center',
      width: 120,
      valign: 'middle',
      formatter: paramsMatter
    },
    {
      field: 'centralSettlementFunds',
      title: '中央结算资金',
      align: 'center',
      width: 100,
      valign: 'middle',
      visible: function (_v, _r, _i) {
        return _r.fundArea_enable
      },
      formatter: paramsMatter
    },
    {
      field: 'provincialSupportingFunds',
      title: '省级配套结算资金',
      align: 'center',
      width: 120,
      valign: 'middle',
      visible: function (_v, _r, _i) {
        return _r.fundArea_enable
      },
      formatter: paramsMatter
    }
  ]

  $('#bootstrap-table').bootstrapTable('destroy').bootstrapTable({
    url: '../json/lyear_statistics.json',
    method: 'get',
    dataType: 'json',
    contentType: 'application/json,charset=utf-8',
    theadClasses: 'table-header-s',
    cache: false, // 不缓存
    striped: false, // 隔行加亮
    queryParamsType: "limit",
    queryParams: {},
    sidePagination: "server", //分页方式：client客户端分页，server服务端分页（*）
    pagination: true, //是否显示分页（*）
    search: false, //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
    strictSearch: false,
    showColumns: false, //是否显示所有的列
    showRefresh: false, //是否显示刷新按钮
    showToggle: false, //是否显示详细视图和列表视图
    clickToSelect: true, //是否启用点击选中行
    fixedColumns: false, // 是否开启固定表头
    fixedRightNumber: 0, //固定右侧表头的数量；
    minimumCountColumns: 2, //最少允许的列数 clickToSelect: true, //是否启用点击选中行
    pageNumber: 1, //初始化加载第一页，默认第一页
    pageSize: 10, //每页的记录行数（*）
    pageList: [10, 25, 50, 100], //可供选择的每页的行数（*）
    showJumpTo: true,
    responseHandler: responseHandler,
    columns: columns,
    onLoadSuccess: function (data) { //加载成功时执行
      console.log('data', data);
    },
    onLoadError: function (res) { //加载失败时执行
      // console.log('res', res);
    },
    // 修改加载内容
    formatLoadingMessage: loadingTemplate
  })
}

/** 请求参数 */
function queryParams(params) {
  var param = {
    pageIndex: Math.ceil(params.offset / params.limit) + 1,
    pageSize: params.limit,
    order: params.order,
    ordername: params.sort,
    startDateTime: $("#dateSearch .startDate").val(),
    endDateTime: $("#dateSearch .endDate").val(),
    search: $("#dateSearch .imuserid").val()
  };
  return param;
}
/** 数据处理 */
function responseHandler(e) {
  if (e && e.data.list.length > 0) {
    return {
      "rows": e.data.list,
      "total": e.data.list.length
    };
  } else {
    return {
      "rows": [],
      "total": 0
    };
  }
}

/** 定义方法 */
function paramsMatter(value, row, index, field) {
  var span = createDom('span');
  span.setAttribute('title', value);
  span.innerHTML = value;
  return span.outerHTML;
}

/** 加载状态模板设置 */
function loadingTemplate(loadingMessage) {
  console.log('loadingMessage', loadingMessage);
  return '正在加载中...'
}